package com.sourcemuch.im.caiba;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import butterknife.BindView;
import cn.wildfire.chat.app.Config;
import cn.wildfire.chat.app.extendsion.BaseActivity;
import cn.wildfire.chat.app.extendsion.utils.BitmapUtils;
import cn.wildfire.chat.app.extendsion.utils.SPUtils;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.app.main.LoginActivity;
import cn.wildfire.chat.app.main.MainActivity;

/**
 * Create by HEKE, 2019/8/19 10:13
 * TODO 用于启动承接之前的界面程序，在没有必要的情况下不用做任何修改
 */
public class ExtendSplashActivity extends BaseActivity {

    @BindView(R2.id.bgImg)
    ImageView bgImg;

    protected Bitmap backgroudBmp;

    private static String[] permissions = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
    };

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void initViews() {
        try {
            /**
             * modify by HEKE , 2019/9/29 15:43 TODO  来自退出，直接进入登入界面
             */
            Intent intent = getIntent();
            if (intent != null) {
                boolean isFromLogout = intent.getBooleanExtra("fromLogout", false);
                if (isFromLogout) {
                    startActivity(new Intent(ExtendSplashActivity.this, LoginActivity.class));
                    finish();
                    return;
                } else {
                    /**
                     * modify by HEKE , 2019/9/29 16:49 TODO 检测程序是否已经启动，直接打开此程序，不进行重复创建
                     */
                    CaiBaChatApp caiBaChatApp = (CaiBaChatApp) getApplicationContext();
                    if (caiBaChatApp.caibaBinder != null) {
                        loginCheck();
                        return;
                    }
                }
            }
            backgroudBmp = BitmapUtils.scaleSplashBackground(this, R.drawable.splash_background);
            if (backgroudBmp != null && !backgroudBmp.isRecycled()) {
                bgImg.setBackground(new BitmapDrawable(getResources(), backgroudBmp));
            }
            if (checkPermission()) {
                next();
            } else {
                requestPermissions(permissions, 100);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_in);
    }

    /**
     * 执行后续操作
     */
    private void next() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!ExtendSplashActivity.this.isFinishing()) {
                    loginCheck();
                    try {
                        if (backgroudBmp != null && !backgroudBmp.isRecycled()) {
                            backgroudBmp.recycle();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 1000);
    }

    /**
     * 登入及进入主界面检测
     */
    protected void loginCheck() {
        try {
            String[] loginInfoArray = SPUtils.getMuches(ExtendSplashActivity.this, "config", new String[]{"id", "token"});
            if (loginInfoArray != null && !TextUtils.isTextEmpty(loginInfoArray[1])) {
                Config.setCurrentLoginUserIdForCacheSet(loginInfoArray[0]);
                Intent intent = new Intent(ExtendSplashActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                startActivity(intent);
            } else {
                startActivity(new Intent(ExtendSplashActivity.this, LoginActivity.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean checkPermission() {
        boolean granted = true;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                granted = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                if (!granted) {
                    break;
                }
            }
        }
        return granted;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "需要相关权限才能正常使用", Toast.LENGTH_LONG).show();
                break;
            }
        }
        next();
    }

}
